/**
 * @author Rivers Zhang
 * 
 */
package edu.njit.hz278.controller.example;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.njit.hz278.bean.example.Customer;
import edu.njit.hz278.bean.example.Empolyee;
import edu.njit.hz278.core.db.Query;
import edu.njit.hz278.core.web.BindingResult;
import edu.njit.hz278.core.web.JSONP;
import edu.njit.hz278.core.web.ModelView;
import edu.njit.hz278.core.web.Param;

public class Module {

	public String funcStrStr(@Param("firm") String firm) {
		return firm;
	}

	public String funcVoidStr() {
		return "linger";
	}

	public String badFunc(int i) {
		System.out.println(i);
		return "linger";
	}

	public String badFunc1(Empolyee e) {
		System.out.println(e.toString());
		return "wtf";
	}

	public String badFunc2(int[] i) {
		System.out.println(Arrays.toString(i));
		return "linger";
	}

	public String funcDoubleStr(@Param("number") double no) {
		return String.valueOf(no);
	}

	public String funcDoubleInt(@Param("fn") double num1, @Param("in") int num2) {
		return String.valueOf(num1 + "/" + num2);
	}

	public String arrayInt(@Param("arr") int[] arr) {
		return Arrays.toString(arr);
	}

	public String bean(@Param("user") Empolyee e) {
		return e.toString();
	}

	public String beans(@Param("users") Empolyee[] es) {
		return Arrays.toString(es);
	}

	public Empolyee[] editBeans(@Param("users") Empolyee[] es) {
		es[0].title = "ceo";
		es[1].title = "cto";
		return es;
	}

	@JSONP
	public Empolyee[] editJsonpBeans(@Param("users") Empolyee[] es) {
		es[0].title = "director";
		es[1].title = "president";
		return es;
	}

	public String raw(HttpServletRequest req, HttpServletResponse resp) {
		return req.getRequestURL().toString();
	}

	public String view() {
		return "example/test";
	}

	public String viewModel(@Param("uname") String user, ModelView mv) {
		mv.put("whoami", user);
		return "example/test_model";
	}

	public String viewBeanModel(@Param("users") Empolyee[] es, ModelView mv) {
		mv.put("users", es);
		return "example/test_bean_model";
	}

	public List<Customer> viewCustomers() throws SQLException {
		Query<Customer> q = new Query<Customer>(Customer.class);
		return q.list();
	}

	public String beanValid(@Param("user") Empolyee e, BindingResult br) {
		if (br.hasError())
			return "example/test.vm";
		return e.toString();
	}

	public Object beanJsonValid(@Param("user") Empolyee e, BindingResult br) {
		if (br.hasError())
			return br.getErrors();
		return e;
	}

	public Object dualBeanJsonValid(
			@Param(value = "employee", forceValid = true) Empolyee e,
			@Param("customer") Customer c, BindingResult br) {
		return c;
	}

	public String beansValid(@Param("users") Empolyee[] es, ModelView mv,
			BindingResult br) {
		if (br.hasError())
			return "example/test";
		mv.put("users", es);
		return "example/test_bean_model";
	}
}
